import urllib.request
import time

def get_price():
	page = urllib.request.urlopen("http://beans.itcarlow.ie/prices.html")
	text = page.read().decode("utf8")
	start=text.find('>$')
	price = float(text[start+2:start+6])
	#print(price)
	print("called")
	return(price)

def send_to_twitter():
	msg="test from command line"
	password_manager = urllib.request.HTTPPasswordMgr()
	password_manager.add_password("Twitter API","http://twitter.com/statuses","yourtwitterid","yourtwitterpassword")
	http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
	page_opener = urllib.request.build_opener(http_handler)
	urllib.request.install_opener(page_opener)
	params=urllib.parse.urlencode( {'status':msg} )
	resp = urllib.request.urlopen("http://twitter.com/statuses/update.json",params)
	resp.read()

requied=input("Show the price immediately (y/n)")

if requied=='y' or requied=='Y':
	price=(get_price())
	#print(price)
	send_to_twitter()
else:
	price=99.99
	while price > 7:
		time.sleep(1)
		price=(get_price())
	send_to_twitter()
	#print ("buy!")
